interface QueueItem<T> {
    item: T;
    cb: (item: T) => void;
}

export class TimerQueue<T> {
    private _queue: QueueItem<T>[] = [];
    private _delay: number = 0;
    private _timerEnabled = false;

    constructor(delay: number = 0) {
        this._delay = delay;
    }

    add(item: T, cb: (item: T) => void) {
        this._queue.push({ item: item, cb: cb });
        if (!this._timerEnabled) {
            this._timerEnabled = true;
            Laya.timer.loop(this._delay, this, this.onTimer);
        }
    }

    private onTimer() {
        let queue = this._queue;
        if (queue.length > 0) {
            let item = queue.shift();
            item.cb(item.item);
        }
        if (queue.length == 0) {
            this._timerEnabled = false;
            Laya.timer.clear(this, this.onTimer);
        }
    }

    clear() {
        this._queue = [];
    }
}
